﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Diagnostics;
using System.Reflection;

namespace ChoViet.Lib.Common
{
    public static class ErrorLog
    {
        public static void WriteLog(Exception exp)
        {
            StreamWriter sw = null;
            try
            {
                // Log format
                string logMessage = string.Format("{0} {1} {2}",
                DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
                exp.Message, exp.StackTrace);

                string logFile = string.Format("{1}.{0}.log", DateTime.Now.ToString("yyyyMMdd"), new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).AbsolutePath);                
                logFile = logFile.Replace("/","\\");
                
                sw = new StreamWriter(logFile, true);
                sw.WriteLine(logMessage);
                sw.Flush();
            }
            catch
            {
                try
                {
                    // Write to event log
                    EventLog eventLog = new EventLog();
                    eventLog.Source = "Enquiry";
                    eventLog.WriteEntry(exp.Message, System.Diagnostics.EventLogEntryType.Error);
                    eventLog.Close();
                }
                catch
                {
                    // None (send and email if it is required)
                }
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
        }
    }
}
